package com.chb.queue;

import java.util.Scanner;

/**
 * 循环队列
 * 1、front初始化0，
 * 2、使用count记录队列元素个数， 通过个数计算最后一个元素的位置
 * 4、队列是否满： count == capacity
 */
public class CircleQueueWithCount {
    private int capacity;
    private int front;
    private int count;
    private int[] queueArr;
    public CircleQueueWithCount(int capacity) {
        this.capacity = capacity;
        this.front = 0;
        this.count = 0;
        this.queueArr = new int[capacity];
    }

    public int size() {
        return count;
    }

    public boolean isEmpty() {
        return count==0;
    }

    public  boolean isFull() {
        return count == capacity;
    }

    // 从尾部添加
    public boolean add(int n) {
        if (isFull()) {
            throw new RuntimeException("Queue is Full!");
        } else {
            queueArr[(front+count)%capacity] = n;
            count += 1;
            return true;
        }
    }

    // 从头部删除
    public int del() {
        if (isEmpty()) {
            throw new RuntimeException("Queue is Empty!");
        } else {
            int e = queueArr[front];
            front = (front + 1) % capacity;
            count--;
            return e;
        }
    }

    // 查看头部
    public int head() {
        if (isEmpty()) {
            throw new RuntimeException("Queue is Empty!");
        } else {
            return queueArr[front];
        }
    }

    public void printQueue() {
        for (int i = front; i < front + size(); i++) {
            System.out.printf("a[%d] = %d,", i%capacity, queueArr[i%capacity]);
        }
        System.out.println();
    }

    public static void main(String[] args) {
        CircleQueueWithCount myQueue = new CircleQueueWithCount(4);
        Scanner in = new Scanner(System.in);
        char key = ' '; // 接受用户输入
        boolean flag = true;
        System.out.println("a(add): 添加元素");
        System.out.println("d(del): 取出元素");
        System.out.println("h(head): 获取头元素");
        System.out.println("p(print): 打印元素");

        while(flag) {
            System.out.println("请输入选项: ");
            key = in.next().charAt(0);
            switch (key) {
                case 'a':
                    System.out.println("请输入一个数: ");
                    int input = in.nextInt();
                    myQueue.add(input);
                    break;
                case 'd':
                    myQueue.del();
                    break;
                case 'h':
                    System.out.println(myQueue.head());
                    break;
                case 'p':
                    myQueue.printQueue();
                    break;
                case 'e':
                    in.close();
                    flag = false;
                    break;
                default:
                    break;
            }

        }
        System.out.println("Exit!!!");
    }

}

